/**
 * 快速测试版 - 只处理前N行数据
 */

const fs = require('fs');
const Papa = require('papaparse');

const TEST_ROWS = 10000; // 只处理前1万行

function analyzeCSVQuick(filePath) {
    return new Promise((resolve, reject) => {
        console.log(`\n快速测试: ${filePath} (仅分析前${TEST_ROWS}行)`);
        console.log('='.repeat(60));

        const fieldStats = {};
        let totalRows = 0;
        let columns = [];
        
        const stream = fs.createReadStream(filePath, { encoding: 'utf-8' });

        Papa.parse(stream, {
            header: true,
            skipEmptyLines: true,
            
            step: function(result, parser) {
                totalRows++;

                if (totalRows === 1 && result.meta.fields) {
                    columns = result.meta.fields;
                    columns.forEach(col => {
                        fieldStats[col] = {
                            values: new Map(),
                            total: 0
                        };
                    });
                }

                columns.forEach(col => {
                    const value = result.data[col];
                    if (!fieldStats[col]) return;
                    
                    fieldStats[col].total++;
                    if (value && value !== '数据不存在') {
                        const count = fieldStats[col].values.get(value) || 0;
                        fieldStats[col].values.set(value, count + 1);
                    }
                });

                if (totalRows >= TEST_ROWS) {
                    parser.abort();
                }
            },

            complete: function() {
                console.log(`✅ 完成！分析了 ${totalRows} 行\n`);
                
                // 判断哪些字段需要分析
                const analyzableFields = [];
                const skippedFields = [];
                
                columns.forEach(col => {
                    const uniqueCount = fieldStats[col].values.size;
                    const uniqueRatio = uniqueCount / totalRows;
                    
                    // 唯一值超过50%认为是ID字段
                    if (uniqueRatio > 0.5 || col.toLowerCase().includes('id')) {
                        skippedFields.push(col);
                        console.log(`⏭️  跳过: ${col} (${uniqueCount}个唯一值)`);
                    } else {
                        analyzableFields.push(col);
                        console.log(`✅ 分析: ${col} (${uniqueCount}个唯一值)`);
                    }
                });
                
                resolve({
                    totalRows,
                    columns,
                    analyzableFields,
                    skippedFields,
                    fieldStats
                });
            },

            error: reject
        });
    });
}

function buildRelationship(filePath, parentCol, childCol) {
    return new Promise((resolve) => {
        const relationMap = new Map();
        let rowCount = 0;
        
        const stream = fs.createReadStream(filePath, { encoding: 'utf-8' });
        
        Papa.parse(stream, {
            header: true,
            skipEmptyLines: true,
            step: function(result, parser) {
                rowCount++;
                const parentValue = result.data[parentCol];
                const childValue = result.data[childCol];
                
                if (parentValue && childValue && 
                    parentValue !== '数据不存在' && 
                    childValue !== '数据不存在') {
                    
                    if (!relationMap.has(parentValue)) {
                        relationMap.set(parentValue, new Set());
                    }
                    relationMap.get(parentValue).add(childValue);
                }
                
                if (rowCount >= TEST_ROWS) {
                    parser.abort();
                }
            },
            complete: function() {
                const mappings = {};
                relationMap.forEach((childSet, parentValue) => {
                    mappings[parentValue] = Array.from(childSet).sort();
                });
                
                resolve({
                    parent: parentCol,
                    child: childCol,
                    mappings
                });
            }
        });
    });
}

function generateReport(results, outputPath) {
    const { totalRows, analyzableFields, skippedFields, fieldStats, relationship } = results;
    
    // 字段枚举表格
    let fieldTablesHtml = '';
    analyzableFields.forEach(col => {
        const stats = fieldStats[col];
        const sortedValues = Array.from(stats.values.entries())
            .sort((a, b) => b[1] - a[1]);
        
        fieldTablesHtml += `
            <div class="field-box">
                <h3>${col}</h3>
                <div class="meta">枚举类型数: <strong>${sortedValues.length}</strong> | 总记录: ${stats.total}</div>
                <table>
                    <tr><th width="40">#</th><th>枚举值</th><th width="100">出现次数</th><th width="80">占比</th></tr>
                    ${sortedValues.slice(0, 30).map(([value, count], idx) => {
                        const percent = (count / stats.total * 100).toFixed(1);
                        return `<tr><td>${idx + 1}</td><td>${value}</td><td>${count}</td><td>${percent}%</td></tr>`;
                    }).join('')}
                    ${sortedValues.length > 30 ? `<tr><td colspan="4" style="text-align:center;color:#999;font-style:italic">... 还有 ${sortedValues.length - 30} 个</td></tr>` : ''}
                </table>
            </div>
        `;
    });
    
    // 关系分析
    let relationHtml = '';
    if (relationship) {
        const sortedMappings = Object.entries(relationship.mappings)
            .sort((a, b) => b[1].length - a[1].length);
        
        relationHtml = `
            <div class="relation-box">
                <h3>${relationship.parent} → ${relationship.child}</h3>
                <div class="relation-list">
                    ${sortedMappings.map(([parent, children]) => `
                        <div class="relation-item">
                            <div class="parent">${parent} <span class="badge">${children.length}</span></div>
                            <div class="children">
                                ${children.map(c => `<span class="tag">${c}</span>`).join('')}
                            </div>
                        </div>
                    `).join('')}
                </div>
            </div>
        `;
    }
    
    const html = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>字段枚举分析</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: "Microsoft YaHei", Arial, sans-serif;
            background: #f0f2f5;
            padding: 20px;
            line-height: 1.6;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 5px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .header {
            background: #1a1a1a;
            color: white;
            padding: 20px 30px;
            border-radius: 5px 5px 0 0;
        }
        .header h1 { font-size: 1.6em; margin-bottom: 5px; }
        .header .info { opacity: 0.8; font-size: 0.9em; }
        .summary {
            display: flex;
            padding: 15px 30px;
            background: #fafafa;
            border-bottom: 1px solid #ddd;
        }
        .summary div {
            flex: 1;
            text-align: center;
            padding: 10px;
        }
        .summary .label { font-size: 0.9em; color: #666; }
        .summary .value { font-size: 1.6em; font-weight: bold; color: #333; margin-top: 5px; }
        .content { padding: 30px; }
        h2 {
            color: #333;
            margin: 25px 0 15px 0;
            padding-bottom: 8px;
            border-bottom: 2px solid #333;
        }
        .skipped {
            background: #fff3cd;
            padding: 12px 15px;
            border-radius: 4px;
            margin-bottom: 25px;
            border-left: 3px solid #ffc107;
        }
        .skipped ul { list-style: none; padding-left: 10px; }
        .skipped li { padding: 3px 0; color: #856404; }
        .field-box, .relation-box {
            margin-bottom: 30px;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 20px;
        }
        .field-box h3, .relation-box h3 {
            color: #0066cc;
            font-size: 1.2em;
            margin-bottom: 10px;
        }
        .meta {
            color: #666;
            margin-bottom: 15px;
            padding: 8px;
            background: #f8f9fa;
            border-radius: 3px;
        }
        .meta strong { color: #0066cc; }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th {
            background: #333;
            color: white;
            padding: 10px;
            text-align: left;
            font-weight: 600;
        }
        td {
            padding: 8px 10px;
            border-bottom: 1px solid #eee;
        }
        tr:nth-child(even) { background: #f9f9f9; }
        tr:hover { background: #f0f0f0; }
        .relation-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 15px;
        }
        .relation-item {
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            padding: 12px;
            background: #fafafa;
        }
        .parent {
            font-weight: bold;
            color: #333;
            margin-bottom: 8px;
            padding-bottom: 8px;
            border-bottom: 1px solid #ddd;
        }
        .badge {
            float: right;
            background: #0066cc;
            color: white;
            padding: 2px 8px;
            border-radius: 10px;
            font-size: 0.85em;
        }
        .children {
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
        }
        .tag {
            background: #e8e8e8;
            padding: 4px 8px;
            border-radius: 3px;
            font-size: 0.85em;
            color: #333;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>字段枚举分析报告</h1>
            <div class="info">测试版本 · 仅分析前${totalRows}行 · ${new Date().toLocaleString('zh-CN')}</div>
        </div>

        <div class="summary">
            <div>
                <div class="label">分析行数</div>
                <div class="value">${totalRows}</div>
            </div>
            <div>
                <div class="label">总字段</div>
                <div class="value">${results.columns.length}</div>
            </div>
            <div>
                <div class="label">分析字段</div>
                <div class="value">${analyzableFields.length}</div>
            </div>
            <div>
                <div class="label">跳过字段</div>
                <div class="value">${skippedFields.length}</div>
            </div>
        </div>

        <div class="content">
            ${skippedFields.length > 0 ? `
                <div class="skipped">
                    <strong>⏭️ 跳过的字段（唯一性字段）：</strong>
                    <ul>${skippedFields.map(f => `<li>• ${f}</li>`).join('')}</ul>
                </div>
            ` : ''}

            <h2>📊 字段关系分析</h2>
            ${relationHtml || '<p style="color:#999;text-align:center;padding:20px">无关系数据</p>'}

            <h2>📋 字段枚举详情</h2>
            ${fieldTablesHtml}
        </div>
    </div>
</body>
</html>`;

    fs.writeFileSync(outputPath, html, 'utf-8');
}

async function main() {
    const filePath = 'output/基本设施.csv';
    const outputPath = 'output/测试报告.html';

    try {
        const results = await analyzeCSVQuick(filePath);
        
        // 分析字段关系
        if (results.analyzableFields.length >= 2) {
            console.log('\n分析字段关系...');
            results.relationship = await buildRelationship(
                filePath,
                results.analyzableFields[0],
                results.analyzableFields[1]
            );
        }
        
        console.log('\n生成报告...');
        generateReport(results, outputPath);
        
        console.log(`\n✅ 报告已生成: ${outputPath}`);
        console.log('双击打开查看效果！\n');
        
    } catch (error) {
        console.error('错误:', error);
    }
}

main();

